package com.simba.server.task;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import org.apache.log4j.Logger;
import com.simba.common.log.LogUtil;
import com.simba.server.components.data.IRecordData;

public class DataRestoreTask extends Thread
{
	private static final Logger logger = Logger.getLogger(DataRestoreTask.class);

	private final BlockingQueue<IRecordData> restoreDataQueue = new LinkedBlockingQueue<IRecordData>();

	public DataRestoreTask()
	{
		this.setName("Data-Resotre-Task");
	}

	public void offerRestoreDataToQueue(IRecordData sorterData)
	{
		if (sorterData == null)
		{
			return;
		}

		this.restoreDataQueue.offer(sorterData);
	}

	@Override
	public void run()
	{
		while (!Thread.currentThread().isInterrupted())
		{
			try
			{
				this.doRestoreData();
			}
			catch (Exception ex)
			{
				if (ex instanceof InterruptedException)
				{
					Thread.currentThread().interrupt();
				}
				LogUtil.LogError(DataRestoreTask.logger,
						"Catch an exception [" + ex.getMessage() + "]");
			}
		}
	}

	protected void doRestoreData() throws InterruptedException
	{
		IRecordData toRecordData = this.restoreDataQueue.take();
		if (toRecordData != null)
		{
			LogUtil.LogError(DataRestoreTask.logger,
					"[DataRestoreTask.doRestoreData] Start to restore : ["
							+ toRecordData.getRecordDataName() + "]");
			toRecordData.restoreData();
		}
	}
}
